package com.bestdreamer.optional;

import java.util.Optional;

public class OptionalTest {

    public static void main(String[] args) {

        Optional<Member> optional = getMemberById();
        optional.ifPresent(member -> {
            System.out.println("会员名称是：" + member.getName());
        });


        Optional<String> emptyOptional = Optional.empty();
        System.out.println(emptyOptional);

        Optional<String> opt1 = Optional.of("李四");
        System.out.println(opt1);

        String name = null;
        Optional<String> opt2 = Optional.ofNullable(name);
        System.out.println(opt2);
        System.out.println(opt2.isPresent());

        // orElse 和 orElseGet 方法类似 ，但参数类型不同。如果 Optional 对象中的值为 null，则执行参数中的函数
        String str1 = Optional.ofNullable(name).orElse("王五");
        System.out.println(str1);

        String str2 = Optional.ofNullable(name).orElseGet(()->"hkrong");
        System.out.println(str2);


    }

    public static Optional<Member> getMemberById(){
        boolean hasName = true;
        if(hasName){
            return Optional.of(new Member("张三"));
        }
        return Optional.empty();
    }

    static class Member{
        private String name;

        public Member(){}
        public Member(String name){
            this.name = name;
        }
        public String getName(){
            return name;
        }
        public void setName(String name){
            this.name = name;
        }
    }
}
